<template>
  <div class="commentsInpus">
    <n-space>
      <n-input
        placeholder="昵称"
        v-model:value="formValue.name"
        autocomplete="off"
      />
      <n-input
        placeholder="邮箱"
        v-model:value="formValue.email"
        autocomplete="off"
      />
    </n-space>
    <n-input
      class="inputTextarea"
      type="textarea"
      placeholder="发条友善的评论...(填写邮箱可以收到回复)"
      v-model:value="formValue.content"
    />
    <n-space class="button" justify="end">
      <n-button round type="primary" @click="click"> 评论 </n-button>
    </n-space>
  </div>
</template>

<script setup lang="ts">
import { NFormItem, NForm, NButton, NInput, NSpace } from "naive-ui";
import type { CreateCommentDto } from "~/api/comments";
import UAParser from "ua-parser-js";
import md5 from "md5";
import { create as apiCreateComments } from "../../api/comments";
let regu = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/;
const props = defineProps({
  commentsParentId: {
    type: Number,
    required: false,
  },
  replyName: {
    type: String,
    required: false,
  },
  replyEmail: {
    type: String,
    required: false,
  },
});
const route = useRoute();
const formValue = ref({
  name: "",
  email: "",
  content: "",
});
const emit = defineEmits(["createAfter"]);

// 提交评论
const click = async () => {
  if (!regu.test(formValue.value.email)) {
    naiveui.message.error("请输入正确的邮件");
    return;
  }
  const parser = new UAParser();
  const ua = parser.getUA();
  const data: CreateCommentDto = {
    name: formValue.value.name,
    email: formValue.value.email,
    content: formValue.value.content,
    resourceId: route.params.id as string,
    ua,
    avatar: handleAvatar(formValue.value.email),
    parent: props.commentsParentId,
    replyName: props.replyName,
    replyEmail: props.replyEmail,
  };
  const res = await apiCreateComments(data);
  if (res?.code == 0) formValue.value.content = "";
  emit("createAfter");
};
const handleAvatar = (email: string) => {
  if (/@qq.com/.test(email)) {
    return `https://q1.qlogo.cn/g?b=qq&nk=${email.split("@")[0]}&s=100`;
  } else {
    return `https://gravatar.loli.net/avatar/${md5(email)}?s=52&d=retro`;
  }
};
</script>
<style lang="scss" scoped>
.inputTextarea {
  margin-top: 10px;
}
.button {
  margin-top: 10px;
}
</style>
